<template>
  <div class="card" style="width: 60%; padding: 30px; margin: auto">
    <h3 style="text-align: center; margin-bottom: 20px">企业管理员信息</h3>

    <el-form ref="formRef" :model="Admin.form" :rules="Admin.rules" label-width="120px">

      <!-- 账号 -->
      <el-form-item label="账号">
        <el-input v-model="Admin.form.username" disabled />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="Admin.form.password" placeholder="请输入密码" :disabled="!isEditing" />
      </el-form-item>
      <!-- 按钮区域 -->
      <el-form-item style="text-align: center">
        <el-button @click="toggleEdit" type="primary" v-if="!isEditing">修改信息</el-button>
        <el-button @click="updateAdmin" type="success" v-else>提交信息</el-button>
        <el-button @click="router.back()" plain>返回</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { parseJwt, getToken } from '@/utils/auth'

const formRef = ref()
// 企业管理员信息（默认只读）
const Admin = reactive({
  form: {
    username: '',
    password: '', 
  },
})

const isEditing = ref(false)
// 模拟从 JWT 解析用户信息并加载数据
const loadAdminInfo = () => {
  const token = getToken()
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }

  const userInfo = parseJwt(token)
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }

  // 获取企业管理员详情（调用后端接口）
axios.get(`/api/admin/info/${userInfo.id}`, {
  headers: {
    Authorization: 'Bearer ' + token
  }
}).then(res => {
  if (res.data.code === 200 && res.data.data) {
    const admin = res.data.data
    Admin.form.username = admin.username
    Admin.form.password = admin.password
  } else {
    ElMessage.error('获取用户信息失败')
  }
  }).catch(err => {
    console.error('请求失败:', err)
    ElMessage.error('网络异常，请重试')
  })
}

// 切换编辑状态
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

// 更新企业管理员信息
const updateAdmin = async () => {
  const userInfo = parseJwt()
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }

  const dataToSend = {
  id: userInfo.id,
  username: Admin.form.username,
  password: Admin.form.password,
}


  try {
    const res = await axios.put('/api/admin/update', dataToSend, {
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('更新成功')
      localStorage.setItem('admin', JSON.stringify(Admin.form))
      toggleEdit() // 返回只读模式
    } else {
      ElMessage.error(res.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('请求错误:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录状态异常，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('网络异常，请重试')
    }
  }
}

onMounted(() => {
  loadAdminInfo()
})
</script>
